/**
 * 全局变量编辑接口测试用例
 *
 * Created by raquelmao on 2020/06/09.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmark = require('./../../../benchmark/analyse-files/self_designed');

module.exports = describe('/PUT functions/:id/variables/output/global.json', function () {
  const administrator = new Administrator();
  const newUserIds = [];
  let tester = {};
  let projectId;
  let globalResults;
  function url(functionId) {
    return `/functions/${functionId}/variables/output/global.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((res) => {
        tester = res;
        newUserIds.push(tester.userId);
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'post');
  common.should.be.tester(uri, url, 'post');

  // 正常编辑
  it('it should POST global', function (done) {
    tester.createRandomProject()
      .then((project) => {
        projectId = project.projectId;
        return project.createRandomVersion();
      })
      .then((projectVersion) => projectVersion.getAllGlobal(benchmark))
      .then((res) => {
        globalResults = res;
        return tester.login();
      })
      .then(() => {
        const promises = globalResults.map((item) => new Promise((resolve) => {
          chai.request(uri)
            .post(url(item.functionId))
            .set('Authorization', `Bearer ${tester.token.accessToken}`)
            .query({ variableName: Object.keys(item.global)[0] })
            .end((err, res) => {
              res.should.have.status(200);
              res.body.should.be.eql(item.global);
              resolve();
            });
        }));
        return Promise.all(promises);
      })
      .then(() => {
        done();
      })
      .catch(done);
  });

  // 不可编辑冻结项目的全局变量
  it('it should fail to post global when the project is frozen', function (done) {
    tester.freezeProject(projectId)
      .then(() => {
        const promises = globalResults.map((item) => new Promise((resolve) => {
          chai.request(uri)
            .post(url(item.functionId))
            .set('Authorization', `Bearer ${tester.token.accessToken}`)
            .query({ variableName: Object.keys(item.global)[0] })
            .end((err, res) => {
              res.should.have.status(403);
              common.should.be.errorMessage(res.body);
              resolve();
            });
        }));
        return Promise.all(promises);
      })
      .then(() => {
        done();
      })
      .catch(done);
  });
});
